package com.ys.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ys.common.result.Result;
import com.ys.common.util.JwtUtil;
import com.ys.modules.system.entity.User;
import com.ys.modules.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/api/system/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @ApiOperation("分页查询用户列表")
    @ApiResponses({
        @ApiResponse(code = 200, message = "返回用户分页列表", response = User.class, responseContainer = "Page")
    })
    @GetMapping("/list")
    public Result<IPage<User>> list(
            @ApiParam(value = "页码", required = true) @RequestParam int page, 
            @ApiParam(value = "每页数量", required = true) @RequestParam int size, 
            @ApiParam(value = "用户名", required = false) @RequestParam(required = false) String username,
            @ApiParam(value = "真实姓名", required = false) @RequestParam(required = false) String realName) {
        Page<User> p = new Page<>(page, size);
        QueryWrapper<User> qw = new QueryWrapper<>();
        if (username != null) qw.like("username", username);
        if (realName != null) qw.like("real_name", realName);
        qw.select(User.class, info -> !info.getColumn().equals("password")); // 不查询密码字段
        return Result.success(userService.page(p, qw));
    }

    @ApiOperation("用户详情")
    @ApiResponses({
        @ApiResponse(code = 200, message = "返回用户详情", response = User.class)
    })
    @GetMapping("/{id}")
    public Result<User> detail(@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        User user = userService.getById(id);
        if (user != null) {
            user.setPassword(null); // 不返回密码
        }
        return Result.success(user);
    }

    @ApiOperation("新增用户")
    @ApiResponses({
        @ApiResponse(code = 200, message = "新增成功", response = Boolean.class)
    })
    @PostMapping
    public Result<Boolean> add(@ApiParam(value = "用户实体", required = true) @RequestBody User user) {
        // 检查用户名是否已存在
        User existUser = userService.findByUsername(user.getUsername());
        if (existUser != null) {
            return Result.fail("用户名已存在");
        }
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return Result.success(userService.save(user));
    }

    @ApiOperation("修改用户")
    @ApiResponses({
        @ApiResponse(code = 200, message = "修改成功", response = Boolean.class)
    })
    @PutMapping
    public Result<Boolean> edit(@ApiParam(value = "用户实体", required = true) @RequestBody User user) {
        // 检查用户名是否已被其他用户使用
        User existUser = userService.findByUsername(user.getUsername());
        if (existUser != null && !existUser.getId().equals(user.getId())) {
            return Result.fail("用户名已存在");
        }
        // 不修改密码
        user.setPassword(null);
        return Result.success(userService.updateById(user));
    }

    @ApiOperation("删除用户")
    @ApiResponses({
        @ApiResponse(code = 200, message = "删除成功", response = Boolean.class)
    })
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        return Result.success(userService.removeById(id));
    }

    @ApiOperation("修改密码")
    @ApiResponses({
        @ApiResponse(code = 200, message = "修改成功", response = Boolean.class)
    })
    @PostMapping("/changePassword")
    public Result<Boolean> changePassword(@RequestBody Map<String, String> passwordData, HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("Bearer ")) {
            return Result.fail("未认证");
        }
        String token = header.substring(7);
        String username = jwtUtil.getUsername(token);
        User user = userService.findByUsername(username);
        if (user == null) {
            return Result.fail("用户不存在");
        }

        String oldPassword = passwordData.get("oldPassword");
        String newPassword = passwordData.get("newPassword");
        
        if (oldPassword == null || newPassword == null) {
            return Result.fail("旧密码和新密码不能为空");
        }
        
        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return Result.fail("旧密码错误");
        }
        
        // 更新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        return Result.success(userService.updateById(user));
    }

    @ApiOperation("重置密码")
    @ApiResponses({
        @ApiResponse(code = 200, message = "重置成功", response = Boolean.class)
    })
    @PostMapping("/resetPassword/{id}")
    public Result<Boolean> resetPassword(@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        // 重置为默认密码 123456
        user.setPassword(passwordEncoder.encode("123456"));
        return Result.success(userService.updateById(user));
    }
} 